import { childrenProps } from "@/components/ProForm/interface";
import Decimal from "decimal.js";
/**
 * @description 将对象内的key添加指定前缀
 */
export function splitParamsObj(obj: object = {}, flag: string = "m_") {
  if (!obj) return {};
  const newObj: any = {};
  Object.keys(obj).forEach(key => {
    if (isValidKey(key, obj)) {
      newObj[flag + key] = obj[key];
    }
  });

  return newObj;
}

/**
 * @description 将数组格式内容转字符串拼接
 */
export const arrJoin = (arr: Array<number | string>, flag = ","): string => {
  return arr?.length ? arr.join(flag) : "";
};

/**
 * @description 将复杂数组中某个字段转字符串拼接
 */
export function arrJoin2(arr: Array<any>, field: string): string {
  const newArr = arr.map(item => item[field]);
  return newArr.join(",");
}

/**
 * @description 将复杂数组中某个字段提取出来
 */
export function arrJoin3(arr: Array<any>, field: string): Array<number | string> {
  const newArr = arr.map(item => item[field]);
  return newArr;
}

/**
 * @param {Array} originArr 原数组
 * @param {String} label 显示的字段
 * @param {String} value 提交的内容
 * @description 转换为下拉框需要数据
 */
export const changeArrField = (originArr: Array<any>, label: string, value: string = ""): childrenProps[] => {
  if (!originArr || !originArr.length) {
    return [];
  }
  const newArr: childrenProps[] = originArr.map(item => {
    return {
      label: item[label],
      value: item[value] || item[label],
      type: "option"
    };
  });

  return newArr;
};

/**
 * @param {Array} originArr 原数组
 * @param {String} label 显示的字段
 * @param {String} value 提交的内容
 * @description 转换为下拉框需要数据
 */
export const changeArrField2 = (originArr: Array<any>, key: string, value: string = "") => {
  if (!originArr || !originArr.length) {
    return [];
  }
  const newArr = originArr.map(item => {
    return {
      key: item[key],
      value: item[value] || item[key]
    };
  });
  return newArr;
};

/**
 * @param {String} value 提交的内容
 * @description 数组字段求和
 */
export const summationArr = (data: Array<any>, field: string) => {
  if (!data?.length) return 0;
  let sum = 0;
  for (let item of data) {
    if (item[field]) {
      sum = new Decimal(sum).add(item[field]).toNumber();
    }
  }
  return sum;
};

/**
 * @description: 更具数组中指定字段进行合并  并对指定字段数量进行求和
 * @param {any} data
 * @param {string} mergeField
 * @param {string} sumField
 */

export const mergeRow = (data: any[], mergeField: string, sumField: string) => {
  if (!data?.length) return [];
  let lodData = JSON.parse(JSON.stringify(data));
  let newArr = [];
  let names = [];

  for (let item of lodData) {
    const index = names.indexOf(item[mergeField]);
    if (index === -1) {
      names.push(item[mergeField]);
      newArr.push(item);
    } else {
      const arr = sumField.split(",");
      for (let key of arr) {
        let a1 = newArr[index][key] || 0;
        let a2 = item[key] || 0;
        newArr[index][key] = new Decimal(a1).add(new Decimal(a2)).toNumber();
      }
    }
  }
  return newArr;
};
